package com.example.movie


import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.baway.movie.entity.MovieTypeEntity
import com.example.base.app.RouterPath
import com.example.common.mvi.BaseMviFragment
import com.example.movie.adapter.MoviePagingDataAdapter
import com.example.movie.adapter.MovieViewPagerAdapter
import com.example.movie.databinding.FragmentMovieBinding
import com.example.movie.intent.MovieViewIntent
import com.example.movie.state.MovieUiState
import com.example.movie.vm.MovieViewModel
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@Route(path = RouterPath.PATH_MOVIE_PAGE)
@AndroidEntryPoint
class MovieFragment : BaseMviFragment<FragmentMovieBinding>() {
    private val mViewModel: MovieViewModel by activityViewModels()
    private var searchHints = mutableListOf("热门影视","今日电影","动作电影")
    private var oneTypeList = mutableListOf<MovieTypeEntity>()
    private var twoTypeList = mutableListOf<MovieTypeEntity>()

    private var fragments = mutableListOf<MovieListFragment>()
    private lateinit var mXPopupBuilder: XPopup.Builder
    private lateinit var mViewPagerAdapter: MovieViewPagerAdapter

    private var leverOneTypeId = 1


    override fun getLayoutId(): Int =R.layout.fragment_movie


    override fun initViews() {
//设置搜索框中搜索热词
        mDataBinding.tbvSearch.setDatas(searchHints)
        //关联Popup组件


        //一级分类筛选
        mDataBinding.tvFilter.setOnClickListener {
            showMovieTypeFilter()
        }

        //创建ViewPagerAdapter
        mViewPagerAdapter = MovieViewPagerAdapter(fragments, this@MovieFragment.childFragmentManager, lifecycle)
        mDataBinding.vpVideo.apply {
            offscreenPageLimit = 3
            adapter = mViewPagerAdapter
        }

        //关联TabLayout与ViewPager2
        TabLayoutMediator(mDataBinding.tabTypeLayout, mDataBinding.vpVideo){tab, position->
            tab.text = twoTypeList[position].typename
        }.attach()
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(MovieViewIntent.LoadLeverOneType)
    }

     override suspend fun collectUIState() {
        mViewModel.uiStateFlow.collectLatest{
            when(it){
                is MovieUiState.LoadLeverOneTypeSuccess -> initLeverOnePopupWindow(it.list)
                is MovieUiState.LoadLeverTwoTypeSuccess -> initLeverTwoType(it.list)
                is MovieUiState.LoadLeverTwoTypeFail -> loadTwoTypeFail()
                is MovieUiState.LoadLeverOneTypeFail -> {}
                else -> {}
            }
        }
    }

    private fun loadTwoTypeFail() {
        twoTypeList.clear()
        fragments.clear()
        mDataBinding.tabTypeLayout.removeAllTabs()

        //添加推荐Tab
        twoTypeList.add(MovieTypeEntity("", 0, -1, 0, "tuijian", "推荐"))
        fragments.add(
            ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", -1).navigation() as MovieListFragment
        )
        //创建Tab标签
        twoTypeList.forEach {
            mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename)
            )
        }

        //更新数据
        mDataBinding.vpVideo.adapter = mViewPagerAdapter
        mViewPagerAdapter.notifyDataSetChanged()

    }


    private fun initLeverTwoType(list: List<MovieTypeEntity>) {
        if (list.isNotEmpty()) {
            twoTypeList.clear()
            fragments.clear()
            mDataBinding.tabTypeLayout.removeAllTabs()

            //添加推荐Tab
            twoTypeList.add(MovieTypeEntity("", 0, -1, 0, "tuijian", "推荐"))
            fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", -1).navigation() as MovieListFragment)
            //添加其他二级分类
            list.forEach {
                twoTypeList.add(it)
                fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", it.id).navigation() as MovieListFragment)
            }
            //创建Tab标签
            twoTypeList.forEach {
                mDataBinding.tabTypeLayout.addTab(
                    mDataBinding.tabTypeLayout.newTab().setText(it.typename)
                )
            }

            //更新数据
            mDataBinding.vpVideo.adapter = mViewPagerAdapter
            mViewPagerAdapter.notifyDataSetChanged()

        }
    }

    private fun initLeverOnePopupWindow(list: List<MovieTypeEntity>){
        if (oneTypeList.size > 0) oneTypeList.clear()
        oneTypeList.addAll(list)

        //加载二级分类
        lifecycleScope.launch {
            mViewModel.channel.send(MovieViewIntent.LoadLeverTwoType(leverOneTypeId))
        }

    }

    private fun showMovieTypeFilter(){
        if (oneTypeList.isNotEmpty()){
            var menuNameList = mutableListOf<String>()
            oneTypeList.forEach {
                menuNameList.add(it.typename)
            }
            mXPopupBuilder = XPopup.Builder(requireContext()).atView(mDataBinding.cltFilter)
            mXPopupBuilder.autoDismiss(true)
            mXPopupBuilder.asAttachList(menuNameList.toTypedArray(), null){position, _ ->
                leverOneTypeId = oneTypeList[position].id
                //加载二级分类
                loadNewTwoTypeById()
            }.show()

        }
    }

    private fun loadNewTwoTypeById() {
        lifecycleScope.launch {
            mViewModel.channel.send(MovieViewIntent.LoadLeverTwoType(leverOneTypeId))
        }

    }

}